#include "Server.h"
#include "MyTask.h"
#include <iostream>

using std::endl;
using std::cout;

Server::Server(int threadNums, int threadTaskQueueSize, 
               string ip, unsigned short port)
    :_threadpool(threadNums, threadTaskQueueSize)
     ,_tcpServer(ip, port)
{
    using namespace std::placeholders;
    _tcpServer.setAllCallbacks(
              std::bind(&Server::_onClose, this, _1)
              ,std::bind(&Server::_onMessage,this,_1)
              ,std::bind(&Server::_onConnection,this,_1)
                              );
}
void Server::start()
{
    _threadpool.start();
    _tcpServer.start();
}
void Server::stop()
{
    _tcpServer.stop();
    _threadpool.stop();
}

void Server::_onConnection(TcpConnectionPtr conn)
{
    cout << conn->toString() << " has connected " << endl;
}
void Server::_onMessage(TcpConnectionPtr conn)
{
    //接收任务
    string msg = conn->recv();
    //封装任务
    Task * task = new MyTask(msg,conn);
    //交给线程池处理
    _threadpool.addTask(task);
}
void Server::_onClose(TcpConnectionPtr conn)
{
    cout << conn->toString() << " has disconnected " << endl;
}
